import { defineStore } from 'pinia'
import { login, getInfo, logout } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    userInfo: {},
    roles: [],
    permissions: []
  }),
  getters: {
    userId: (state) => state.userInfo?.id,
    username: (state) => state.userInfo?.username,
    realName: (state) => state.userInfo?.real_name,
    avatar: (state) => state.userInfo?.avatar || 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif'
  },
  actions: {
    // 登录
    async login(loginData) {
      try {
        const res = await login(loginData)
        const { token } = res.data
        this.token = token
        setToken(token)
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 获取用户信息
    async getUserInfo() {
      try {
        const res = await getInfo()
        const { user, roles, permissions } = res.data
        
        this.userInfo = user
        this.roles = roles || []
        this.permissions = permissions || []
        
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    },
    
    // 登出
    async logout() {
      try {
        await logout()
      } catch (error) {
        console.error('登出失败', error)
      } finally {
        this.resetState()
        router.push('/login')
      }
    },
    
    // 清除用户状态
    resetState() {
      this.token = ''
      this.userInfo = {}
      this.roles = []
      this.permissions = []
      removeToken()
    },
    
    // 检查是否有特定权限
    hasPermission(permission) {
      return this.permissions.includes(permission)
    },
    
    // 检查是否有特定角色
    hasRole(role) {
      return this.roles.some(r => r.code === role)
    }
  }
}) 